package com.group.util;

import com.group.model.Student;
import com.group.controller.StudentController;

import java.io.*;
import java.nio.charset.StandardCharsets;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.util.Collection;
import java.util.Map;
import java.util.Random;

/**
 * @author lenovo
 */
public class StudentDataLoader {
    //学生数据的导入、导出、模拟生成等核心任务
    public static void loadFromFile(String path) {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) {
            //用 UTF-8 编码读取文件，防止中文乱码
            com.group.controller.StudentController.deleteAllOnlyMap();
            //调用控制器里的方法，清空当前程序内存中的学生数据
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("\t");
                //split("\t")：用制表符分割字符串
                if (parts.length < 7) {continue;}

                String id = parts[0];
                String name = parts[1];
                String gender = parts[2];
                String birth = parts[3];

                Student s = new Student(id, name, gender, birth);
                for (int i = 4; i < parts.length; i++) {
                    String[] courseScore = parts[i].split(":");
                    //split(":")：将其拆为课程名和成绩值
                    if (courseScore.length == 2) {
                        try {
                            String course = courseScore[0];
                            double score = Double.parseDouble(courseScore[1]);
                            //将字符串转为 double 类型
                            s.addScore(course, score);
                        } catch (NumberFormatException ignored) {}
                    }
                }

                StudentController.addOnlyMap(s);
            }
        } catch (IOException e) {
            System.err.println("读取学生数据失败：" + e.getMessage());
        }
    }
    public static void exportToExcel(String filePath, Collection<Student> students) throws Exception {//filePath：导出的 Excel 文件路径
        Workbook workbook = new XSSFWorkbook();
        //创建一个Excel文件
        Sheet sheet = workbook.createSheet("学生数据");
        // 创建一个工作表并命名

        String[] headers = {"学号", "姓名", "性别", "出生日期", "Math", "Java", "PE"};
        //表头
        Row headerRow = sheet.createRow(0);
        // 第0行作为表头
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
            //createCell(i)创建第 i 列,setCellValue写入字符串到单元格
        }

        int rowIndex = 1;
        for (Student s : students) {
            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(s.getId());
            row.createCell(1).setCellValue(s.getName());
            row.createCell(2).setCellValue(s.getGender());
            row.createCell(3).setCellValue(s.getBirth());

            Map<String, Double> scores = s.getScores();
            row.createCell(4).setCellValue(scores.getOrDefault("Math", 0.0));
            //如果学生缺某门课的成绩，则默认写入 0.0
            row.createCell(5).setCellValue(scores.getOrDefault("Java", 0.0));
            row.createCell(6).setCellValue(scores.getOrDefault("PE", 0.0));
        }

        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            workbook.write(fos);
            // 将内存中的数据写入到文件
        }
        workbook.close();// 关闭 workbook，释放内存
    }
    private static final String[] LAST_NAMES = {"赵", "钱", "孙", "李", "周", "吴", "郑", "王"};
    private static final String[] FIRST_NAMES = {"伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军"};
    private static final Random RAND = new Random();

    // 生成随机姓名
    private static String randomName() {
        return LAST_NAMES[RAND.nextInt(LAST_NAMES.length)] + FIRST_NAMES[RAND.nextInt(FIRST_NAMES.length)];
    }

    // 生成随机性别
    private static String randomGender() {
        return RAND.nextBoolean() ? "男" : "女";
    }

    // 生成随机生日
    private static String randomBirthday() {
        int year = 2000 + RAND.nextInt(5);
        // 2000 - 2004
        int month = 1 + RAND.nextInt(12);
        int day = 1 + RAND.nextInt(28);
        return String.format("%04d-%02d-%02d", year, month, day);
    }

    // 生成正态分布的成绩（中心 80，标准差 10）
    private static double randomScore() {
        double score = 80 + RAND.nextGaussian() * 10;
        score = Math.max(0, Math.min(100, score));
        // 限制 0~100
        return Math.round(score * 10) / 10.0;
    }

    //  你要调用的方法：生成并保存
    public static void generateAndSave(String path, int count) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8));
        int idNum = 100000;

        for (int i = 0; i < count; i++) {
            String id = "2024" + (idNum + i);
            String name = randomName();
            String gender = randomGender();
            String birth = randomBirthday();
            double math = randomScore();
            double java = randomScore();
            double pe = randomScore();

            String line = String.format("%s\t%s\t%s\t%s\tMath:%.1f\tJava:%.1f\tPE:%.1f", id, name, gender, birth, math, java, pe);
            writer.write(line);
            writer.newLine();
        }

        writer.close();
    }

}

